package org.web2024.service.serviceimp;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.web2024.dao.Result;
import org.web2024.dao.User;
import org.web2024.dao.UserdetailsImp;
import org.web2024.mapper.UserMapper;
import org.web2024.service.LoginService;
import org.web2024.utils.jwtUtil;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
public class LoginServiceImp implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper mp;
    @Override
    public Result Login(User user) {
        // 创建认证令牌，包含用户名和密码
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user.getUser_no(), user.getUser_psw());

        // 打印当前登录的用户名和密码
        System.out.println("当前登录:"+user.getUser_no()+"  "+user.getUser_psw());

        // 使用AuthenticationManager进行身份验证
        Authentication authentication = authenticationManager.authenticate(token);

        // 将认证后的用户信息转换为自定义的UserdetailsImp对象
        UserdetailsImp userdetailsImp = (UserdetailsImp) authentication.getPrincipal();

        // 创建一个HashMap用于存储JWT的负载信息
        HashMap<String,Object> claims=new HashMap<>();
        HashMap<String,Object> data=new HashMap<>();
        // 将用户ID添加到负载信息中
        claims.put("no",userdetailsImp.getUser().getUser_no());

        String userid="login:"+userdetailsImp.getUser().getUser_no();//存储用户信息的id

        redisTemplate.opsForValue().set(userid,userdetailsImp,1, TimeUnit.HOURS);

        // 使用jwtUtil生成JWT令牌
        String jwt= jwtUtil.getToken(claims);
        data.put("token",jwt);
        data.put("userpermission",userdetailsImp.getPermission());
        // 返回成功结果，包含生成的JWT令牌
        return Result.success(data);
    }

    @Override
    public Result Logout() {
        UserdetailsImp userimp = (UserdetailsImp) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        redisTemplate.delete("login:"+userimp.getUser().getUser_no());
        return Result.success();
    }

    public Result update(String oldpsw, String newpsw) {
        UserdetailsImp userdetailsImp = (UserdetailsImp) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userNO = userdetailsImp.getUser().getUser_no();
        String psw = mp.selectpsw(userNO);
        if(!passwordEncoder.matches(oldpsw,psw)){
            return Result.fail("密码错误");
        }
        mp.updatePsw(passwordEncoder.encode(newpsw), userNO);
        redisTemplate.delete("login:"+userNO);
        return Result.success();
    }
}
